/*
 *    Copyright 2008-2009 The PoCo Team
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.asemantics.poco.converters;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.converters.AbstractConverter;

/**
 * 
 * @author Simone Tripodi
 * @version $Id: EnumConverter.java 240 2009-12-20 00:19:46Z simone.tripodi@gmail.com $
 */
@SuppressWarnings("unchecked")
public final class EnumConverter extends AbstractConverter {

    private final Class enumClass;

    public EnumConverter(Class enumClass) {
        this(enumClass, null);
    }

    public EnumConverter(Class enumClass, Object defaultValue) {
        super(defaultValue);
        this.enumClass = enumClass;
    }

    @Override
    protected Object convertToType(Class type, Object value) throws Throwable {
        try {
            return Enum.valueOf(this.enumClass, value.toString().toLowerCase());
        } catch (IllegalArgumentException e) {
            throw new ConversionException(e);
        }
    }

    @Override
    protected String convertToString(Object value) throws Throwable {
        return ((Enum) value).name();
    }

    @Override
    protected Class getDefaultType() {
        return this.enumClass;
    }

}
